DFS is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node and explores as far as possible along each branch before backtracking.
Key Characteristics:
// Recommended for very deep trees to avoid stack overflow
void dfsIterative(Node* root) {
if (!root) return;
std::stack<Node*> s;
s.push(root);
while (!s.empty()) {
Node* curr = s.top();
s.pop();
std::cout << curr->val << " ";
// Push right first so left is processed first (LIFO)
if (curr->right) s.push(curr->right);
if (curr->left) s.push(curr->left);
}
}
// The most common and concise way
void dfsRecursive(Node* node) {
if (!node) return;
std::cout << node->val << " "; // Pre-order visit
dfsRecursive(node->left);
dfsRecursive(node->right);
}